/**
 * $Revision: 1.0 $
 * $Author: Eric Yang $
 * $Date: Aug 7, 2009 10:44:51 PM $
 *
 * Author: Eric Yang
 * Date  : Aug 7, 2009 10:44:51 PM
 *
 */
package com.gooex.service.organization.impl;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.c4j.string.StringTools;
import org.c4j.system.web.hibernate.BaseHibernateService;

import com.gooex.domain.organization.Group;
import com.gooex.service.organization.AuthorityContext;
import com.gooex.service.organization.IGroupManager;
import com.gooex.service.organization.exception.GroupException;

/**
 * @author Eric Yang
 * @version 1.0
 */
public class GroupManagerImpl extends BaseHibernateService implements IGroupManager {

	private static final Log logger = LogFactory.getLog(GroupManagerImpl.class);

	public Group getGroup(String id) {
		if (StringTools.isBlankOrNull(id))
			return null;
		return (Group) getHibernateTemplate().get(Group.class, id);
	}

	public List<Group> getGroups() {
		return getHibernateTemplate().find("from Group");
	}

	public Group getGroupByName(String name) {
		String hql = "from " + Group.class.getName() + " where name=?";
		List<Group> groups = getHibernateTemplate().find(hql, name);
		if (groups != null && groups.size() == 1)
			return groups.get(0);
		return null;
	}

	public void saveGroup(Group group) {
		if (StringTools.isBlankOrNull(group.getId())) {
			group.setId(null);
		}
		getHibernateTemplate().saveOrUpdate(group);
	}

	public void removeGroup(Group group) throws GroupException {
		group = getGroup(group.getId());
		if (AuthorityContext.getSuperGroup().equals(group)) {
			logger.debug("Group[" + group.getName() + "] is super group, can't be removed!");
			throw new GroupException("Can't remove super group!");
		}
		getHibernateTemplate().delete(group);
	}

}
